package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    //http://localhost:8080/setmeal

    /**
     * 添加套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(cacheNames = "SetmealList",key = "#setmealDto.categoryId+'_'+#setmealDto.status")
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        setmealService.saveWithDish(setmealDto);
        return R.success("添加成功");
    }

    //http://localhost:8080/setmeal/page?page=1&pageSize=10

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "name", defaultValue = "") String name
    ) {
        //分页对象
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        //设置最终返回的分页对象
        Page<SetmealDto> setmealDtoPage = new Page<>();
        //设置条件
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.like(StringUtils.hasLength(name), Setmeal::getName, name);
        //分页查询
        Page<Setmeal> pageInfo = setmealService.page(setmealPage, setmealLambdaQueryWrapper);

        List<Setmeal> records = pageInfo.getRecords();

        records = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null) {
                setmealDto.setCategoryName(category.getName());
            }

            return setmealDto;
        }).collect(Collectors.toList());

        //复制page对象属性值
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");

        setmealPage.setRecords(records);

        return R.success(pageInfo);
    }

    //http://localhost:8080/setmeal?ids=1415580119015145474,1494609908095590401

    /**
     * 批量删除套餐
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(cacheNames = "SetmealList",allEntries = true)
    public R<String> delete(@RequestParam("ids") List<Long> ids) {
        if (ids != null && ids.size() != 0) {
            setmealService.deleteWithDish(ids);
            return R.success("删除成功");
        }

        return R.error("没有选择任何选项,删除失败");
    }

    /**
     * 更新套餐
     * @param status
     * @param ids
     * @return
     */
    //http://localhost:8080/setmeal/status/0?ids=1517679161232109570,1517679247555080193
    @PostMapping("/status/{status}")
    @CacheEvict(cacheNames = "SetmealList",allEntries = true)
    public R<String> updateStatus(
            @PathVariable("status") Integer status,
            @RequestParam("ids") Long[] ids
    ) {
        List<Setmeal> setmealList = Arrays.stream(ids).map((item) -> {
            Setmeal setmeal = new Setmeal();
            setmeal.setId(item);
            setmeal.setStatus(status);
            return setmeal;
        }).collect(Collectors.toList());
        setmealService.updateBatchById(setmealList);
        return R.success("修改成功");
    }

    //http://localhost:8080/setmeal/list?categoryId=1413386191767674881&status=1
    //查询套餐
    @GetMapping("/list")
    @Cacheable(cacheNames = "SetmealList", key = "#setmeal.categoryId+'_'+#setmeal.status", unless = "#result.data.size()==0")
    public R<List<Setmeal>> getList(Setmeal setmeal) {
        //设置条件
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        setmealLambdaQueryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        setmealLambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);
        //查询
        List<Setmeal> setmealList = setmealService.list(setmealLambdaQueryWrapper);

       /* List<SetmealDto> setmealDtoList = setmealList.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null) {
                setmealDto.setCategoryName(category.getName());
            }
            //找规格
            LambdaQueryWrapper<SetmealDish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishLambdaQueryWrapper.eq(SetmealDish::getDishId, item.getCategoryId());
            List<SetmealDish> setmealDishList = setmealDishService.list(dishLambdaQueryWrapper);
            setmealDto.setSetmealDishes(setmealDishList);
            return setmealDto;
        }).collect(Collectors.toList());*/


        return R.success(setmealList);
    }

    //http://localhost:8080/setmeal/1415580119015145474

    /**
     * 查询单个套餐
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getOne(@PathVariable("id") Long id) {

        Setmeal setmealOne = setmealService.getById(id);

        if (setmealOne != null) {
            //创建setmealDto对象
            SetmealDto setmealDto = new SetmealDto();
            //条件查询套餐关联的菜品集合
            LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            setmealDishLambdaQueryWrapper.eq(SetmealDish::getSetmealId, setmealOne.getId());
            List<SetmealDish> setmealDishList = setmealDishService.list(setmealDishLambdaQueryWrapper);

            //拷贝属性
            BeanUtils.copyProperties(setmealOne, setmealDto);
            //设置集合
            setmealDto.setSetmealDishes(setmealDishList);

            //查询分类名称
            LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
            categoryLambdaQueryWrapper.eq(Category::getId, setmealOne.getCategoryId());
            Category category = categoryService.getOne(categoryLambdaQueryWrapper);

            //设置分类名称
            setmealDto.setCategoryName(category.getName());

            return R.success(setmealDto);
        }

        return R.error("查询失败");
    }

}
